package top.snoweagle.simple.console.security.auth;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import top.snoweagle.simple.console.common.domain.http.UserSession;
import top.snoweagle.simple.console.common.domain.system.User;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * Created by snoweagle on 5/28/16.
 */
@Component
public class TokenManager {

    private final long SESSION_TIME = TimeUnit.MINUTES.toMillis(3);
    private Map<String,UserSession> tokenCache = new ConcurrentHashMap<>();

    public UserSession newUserSession(Long userId,String fullName){
        String token = UUID.randomUUID().toString().replace("-",
                "");
        return cache(new UserSession(userId,fullName,token,getExpireTime()));
    }
    public UserSession cache(UserSession session){
        tokenCache.put(session.getToken(), session);
        return session;
    }

    public boolean check(String token){
        if(StringUtils.isEmpty(token)){
            return false;
        }
       long expireTime =  tokenCache.get(token).getExpireTime();
        if(new Date().getTime()>expireTime){
            //超时
            tokenCache.remove(token);
            return false;
        }else{
            tokenCache.get(token).setExpireTime(getExpireTime());
            return true;
        }
    }
    public UserSession get(String token){
        return tokenCache.get(token);
    }
    public void remove(String token){
        tokenCache.remove(token);
    }
    private long getExpireTime(){
        return new Date().getTime()+ SESSION_TIME;
    }
}
